﻿using CloudMusic.API;
using CloudMusic.Helper;
using CloudMusic.Model;
using CloudMusic.UC;
using DMSkin.Core.MVVM;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace CloudMusic.ViewModel
{
    /// <summary>
    /// 这是播放页面的基类
    /// </summary>
    public class MusicViewModelBase : ViewModelBase
    {
        #region 定义
        /// <summary>
        /// 添加歌曲到播放列表
        /// </summary>
        public static event EventHandler songListEvent;
        /// <summary>
        /// 对歌曲的喜欢状态-0/不喜欢-1/喜欢
        /// </summary>
        public static event EventHandler likesState;
        /// <summary>
        /// 选中的歌曲
        /// </summary>
        public static PlayModel SelectMusicInfo { get; set; }
        /// <summary>
        /// 播放按钮状态
        /// </summary>
        private PlayState _playState = PlayState.Play;
        public PlayState PlayBtnState
        {
            get
            {
                return _playState;
            }
            set
            {
                _playState = value;
                OnPropertyChanged("PlayBtnState");
            }
        }
        /// <summary>
        /// 播放列表数据
        /// </summary>
        public static ObservableCollection<PlayModel> PlayInfo { get; set; } = new ObservableCollection<PlayModel>();
        /// <summary>
        /// 播放历史列表
        /// </summary>
        public static ObservableCollection<PlayModel> HistoryMusicList { get; set; } = new ObservableCollection<PlayModel>();
        /// <summary>
        /// 音乐列表
        /// </summary>
        private ObservableCollection<MusicModel> musicList;
        public ObservableCollection<MusicModel> MusicList
        {
            get
            {
                if (musicList == null)
                {
                    musicList = new ObservableCollection<MusicModel>();
                }
                return musicList;
            }
            set
            {
                musicList = value;
                //SongSheetListHelper.MainMusicList = musicList;
                OnPropertyChanged("MusicList");
            }
        }
        /// <summary>
        /// 播放按钮ICON位置
        /// </summary>
        private string playBtnLeft;
        public string PlayBtnLeft
        {
            get { return playBtnLeft; }
            set { playBtnLeft = value; OnPropertyChanged("PlayBtnLeft"); }
        }
        /// <summary>
        /// 当前播放的歌曲的信息
        /// </summary>
        public PlayModel selectedMusic;
        public PlayModel SelectedMusic
        {
            get { return selectedMusic; }
            set
            {
                selectedMusic = value;
                OnPropertyChanged("SelectedMusic");
            }
        }
        #endregion

        #region 播放

        #region 选中播放
        public ICommand PlayCommand
        {
            get
            {
                return new DelegateCommand(obj =>
                {
                    try
                    {
                        if (obj != null && obj.ToString().Length > 0)
                        {
                            MusicModel item = (MusicModel)obj;
                            if (SelectMusicInfo != null && SelectMusicInfo.Id == item.Id) return;
                            var tList = ObjectToEntityHelper.ToUnityByJson<PlayModel>(item);
                            if (tList.Subtitle != null) tList.Subtitle = tList.Subtitle.Substring(1, tList.Subtitle.Length - 2);
                            SelectedMusic = SelectMusicInfo = tList;
                            songListEvent?.Invoke(tList.Id, null);
                            PlayManager.Play(SelectedMusic);
                            var mm = ObjectToEntityHelper.ConvertObjectByJson<PlayModel>(PlayListHelper.MainMusicList);
                            if (PlayInfo.Any(t => t.Id == item.Id)) return;
                            PlayInfo.Clear();
                            mm.ForEach(p => PlayInfo.Add(p));

                        }
                    }
                    catch (Exception ex) { string ss = ex.Message; }
                });
            }
        }
        #endregion

        #region 播放列表播放事件
        public ICommand PlayLisyPlayCommand
        {
            get
            {
                return new DelegateCommand(obj =>
                {
                    if (obj != null && obj.ToString().Length > 0)
                    {

                        PlayModel item = (PlayModel)obj;
                        if (SelectMusicInfo != null && SelectMusicInfo.Id == item.Id) return;
                        PlayManager.Play(item);
                        SelectMusicInfo = item;
                    }
                });
            }
        }

        #endregion

        #region 播放当前歌单所有歌曲

        /// <summary>
        /// 其他播放列表所有
        /// </summary>
        public ICommand PlayAllCommand
        {
            get
            {
                return new DelegateCommand(obj =>
                {
                    try
                    {
                        if (obj != null)
                        {
                            //DataGrid Grid = (DataGrid)obj;
                            ObservableCollection<MusicModel> model = (ObservableCollection<MusicModel>)obj;
                            //MusicModel item = (MusicModel)obj;
                            var tList = ObjectToEntityHelper.ConvertObjectByJson<PlayModel>(model);

                            if (PlayListHelper.MainMusicList != null)
                            {
                                PlayInfo.Clear();
                                PlayListHelper.MainMusicList.Clear();
                            }
                            tList.ForEach(p => PlayListHelper.MainMusicList.Add(p));
                            tList.ForEach(p => PlayInfo.Add(p));
                            PlayBtnState = PlayState.Pause;
                            SelectMusicInfo = PlayListHelper.MainMusicList[0];
                            SelectMusicInfo.Playing = true;
                            PlayManager.Play(PlayListHelper.MainMusicList[0]);
                        }
                    }
                    catch (Exception) { }
                });
            }
        }
        /// <summary>
        /// 排行榜播放列表
        /// </summary>
        public ICommand PlayPHAllCommand
        {
            get
            {
                return new DelegateCommand(obj =>
                {
                    try
                    {
                        if (obj != null)
                        {
                            var tList = ObjectToEntityHelper.ConvertObjectByJson<PlayModel>(obj);

                            if (PlayListHelper.MainMusicList != null)
                            {
                                PlayInfo.Clear();
                                PlayListHelper.MainMusicList.Clear();
                            }
                            tList.ForEach(p => PlayListHelper.MainMusicList.Add(p));
                            tList.ForEach(p => PlayInfo.Add(p));
                            PlayBtnState = PlayState.Pause;
                            SelectMusicInfo = PlayListHelper.MainMusicList[0];
                            SelectMusicInfo.Playing = true;
                            PlayManager.Play(PlayListHelper.MainMusicList[0]);
                        }
                    }
                    catch (Exception) { }
                });
            }
        }
        #endregion

        #region 添加歌曲到播放列表
        public ICommand PlayAddCommand
        {
            get
            {
                return new DelegateCommand(obj =>
                {
                    try
                    {
                        if (obj != null)
                        {

                            //DataGrid Grid = (DataGrid)obj;
                            ObservableCollection<MusicModel> dataGrid = (ObservableCollection<MusicModel>)obj;
                            var tList = ObjectToEntityHelper.ConvertObjectByJson<PlayModel>(dataGrid);
                            var index = PlayListHelper.MainMusicList.IndexOf(PlayListHelper.MainMusicList.FirstOrDefault(t => t.Id == SelectMusicInfo.Id));
                            for (int i = 0; i < dataGrid.Count; i++)
                            {
                                PlayModel music = new PlayModel
                                {
                                    Index = dataGrid[i].Id.ToString(),
                                    Url = dataGrid[i].Url,
                                    Name = dataGrid[i].Name,
                                    CanPlay = true,
                                    Subtitle = dataGrid[i].Subtitle,
                                    Size = dataGrid[i].Size,
                                    Album = dataGrid[i].Album,
                                    Artist = dataGrid[i].Artist,
                                    TimeStr = dataGrid[i].TimeStr,
                                    DownLoad = dataGrid[i].DownLoad,
                                    PicUrl = dataGrid[i].PicUrl,
                                    Id = dataGrid[i].Id,
                                    SongId = dataGrid[i].SongId,
                                    Type = dataGrid[i].Type,
                                    SingerId = dataGrid[i].SingerId,
                                    AlbumId = dataGrid[i].AlbumId,
                                    VIPVis = dataGrid[i].VIPVis,
                                    STVis = dataGrid[i].STVis,
                                    SQVis = dataGrid[i].SQVis,
                                    MVVis = dataGrid[i].MVVis,
                                    CoverTitle = dataGrid[i].CoverTitle,
                                    Pop = dataGrid[i].Pop,
                                    Playing = dataGrid[i].Playing,
                                    ChargeInfoList = GetChargeInfos(dataGrid[i].ChargeInfoList)
                                };
                                PlayListHelper.MainMusicList.Insert((index + 1) + i, music);
                                PlayInfo.Insert((index + 1) + i, music);
                            }
                        }
                    }
                    catch (Exception) { }

                });
            }
        }
        #endregion

        #endregion

        #region 喜欢与否
        public ICommand SetOrRemoveLike
        {
            get
            {
                return new DelegateCommand(obj =>
                {
                    try
                    {
                        if (obj != null && obj.ToString().Length > 0)
                        {
                            var item = ObjectToEntityHelper.ToUnityByJson<MusicModel>(obj);

                            //MusicModel item = (MusicModel)obj;
                            if (item.Like == 1)
                            {
                                changeLikeState(item.Id, 0);
                            }
                            else
                            {
                                changeLikeState(item.Id, 1);
                            }
                        }
                    }
                    catch (Exception ex) { MyCustomControlLibrary.MMessageBox.ShowAlert(ex.Message, Orientation.Horizontal, null, "#323232", false); }
                });
            }
        }

        private void changeLikeState(long id, int state)
        {
            var list = "";
            var strMsg = "";
            bool lk = state == 0 ? false : true;
            var cookie = PlayListHelper.UserInfos.Count == 0 ? "" : PlayListHelper.UserInfos[0].Cookie;
            list = CommonHelper.Get("http://localhost:3000/like?id=" + id + "&like=" + lk + "&cookie=" + cookie);
            if (!list.Contains("code"))
            {
                strMsg = "喜欢失败";
            }
            else
            {
                JObject jo = (JObject)JsonConvert.DeserializeObject(list);
                if (Convert.ToInt32(jo["code"].ToString()) != 200)
                {
                    strMsg = jo["code"].ToString() == "301" ? jo["msg"].ToString() : "喜欢失败";
                }
                else
                {
                    if (SelectedMusic != null)
                    {
                        if (id == SelectedMusic.Id)
                        {
                            SelectedMusic.Like = state;
                        }
                        else
                        {
                            var index = PlayListHelper.MainMusicList.IndexOf(PlayListHelper.MainMusicList.FirstOrDefault(t => t.Id == id));
                            if (index > 0) PlayListHelper.MainMusicList[index].Like = state;
                        }

                    }
                    else
                    {
                        var index = PlayListHelper.MainMusicList.IndexOf(PlayListHelper.MainMusicList.FirstOrDefault(t => t.Id == id));
                        if (index > 0) PlayListHelper.MainMusicList[index].Like = state;
                    }
                    likesState?.Invoke(id, null);
                    strMsg = state.ToString() == "1" ? "已添加到我喜欢的音乐" : "取消喜欢成功";
                }
            }

            MyCustomControlLibrary.MMessageBox.ShowAlert(strMsg, Orientation.Horizontal, null, "#323232", false);
        }
        #endregion

        #region 是否显示歌曲列表
        private bool displayMusicList;
        /// <summary>
        /// 是否显示歌曲列表
        /// </summary>
        public bool DisplayMusicList
        {
            get { return displayMusicList; }
            set
            {
                displayMusicList = value;
                OnPropertyChanged("DisplayMusicList");
            }
        }

        public void ShowMusicList(bool show = true)
        {
            if (MusicList.Count > 0)
            {
                DisplayMusicList = show;
            }
            else
            {
                //歌曲列表为空的时候 隐藏 歌曲列表视图
                DisplayMusicList = false;
            }
        }
        #endregion

        #region 歌曲品质封装
        public static List<ChargeInfo> GetChargeInfos(List<ChargeInfo> ch)
        {
            if (ch == null) return null;
            List<ChargeInfo> chargeInfos = new List<ChargeInfo>();
            for (int i = 0; i < ch.Count; i++)
            {
                chargeInfos.Add(new ChargeInfo
                {
                    Rate = ch[i].rate,
                    ChargeMessage = ch[i].chargeMessage,
                    chargeType = ch[i].chargeType,
                    chargeUrl = ch[i].chargeUrl
                });
            }
            return chargeInfos;
        }
        #endregion

        public void GetPlayList(MusicModel music)
        {
            if (PlayListHelper.MainMusicList.Count > 0) return;
            if (music.Type == 1)
            {
                PlayListHelper.MainMusicList.Clear();
                var list = CommonHelper.GetEquipList<SongSheetModel>(1, "http://localhost:3000/playlist/detail?id=" + music.SongId + "");
                if (list.code == 404) return;
                for (int i = 0; i < list.playlist.tracks.Count; i++)
                {
                    MusicModel songSheetList = new MusicModel
                    {
                        Index = i > 10 ? i.ToString() : "0" + (i + 1).ToString(),
                        Album = list.playlist.tracks[i].al.name,
                        AlbumId = list.playlist.tracks[i].al.id,
                        Name = list.playlist.tracks[i].name,
                        Id = list.playlist.tracks[i].id,
                        Artist = list.playlist.tracks[i].ar[0].name,
                        SingerId = list.playlist.tracks[i].ar[0].id,
                        Type = 1,
                        PicUrl = list.playlist.tracks[i].al.picUrl,
                    };
                    //SongSheetListHelper.MainMusicList.Add(songSheetList);
                }
            }
            else
            {
                if (File.Exists("LocalMusic.json"))
                {
                    PlayListHelper.MainMusicList.Clear();
                    //尝试从 配置文件中读取 上次 增加的 播放列表
                    string json = File.ReadAllText("LocalMusic.json");
                    if (!string.IsNullOrEmpty(json))
                    {
                        List<MusicModel> list = JsonConvert.DeserializeObject<List<MusicModel>>(json);
                        foreach (var item in list)
                        {
                            //  PlayListHelper.MainMusicList.Add(item);
                        }
                    }
                }
            }
        }

    }
}
